package com.zmn.oms.business.impl.orderfinalpricequotation;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.dro.phenomenon.PhenomenonDRO;
import com.zmn.base.common.data.dubbo.interfaces.phenomenon.PhenomenonListRemoteService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.base.price.common.dto.fixed.FixedPhenoFilterItemQuery;
import com.zmn.base.price.dubbo.interfaces.calculate.FixedFlowRemoteService;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.orderfinalpricequotation.OrderFinalPriceQuotationBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dio.finalpricequotation.OrderFinalPriceQuotationDataDIO;
import com.zmn.oms.common.dro.finalpricequotation.OrderFinalPriceQuotationDRO;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotation;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotationQuery;
import com.zmn.oms.model.entity.quotation3.OrderFaultPhenomenon;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.quotation3.OrderFaultPhenomenon;
import com.zmn.oms.model.entity.quotation3.OrderQuotationProcess;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.orderfinalpricequotation.OrderFinalPriceQuotationService;
import com.zmn.oms.services.interfaces.quotation3.OrderFaultPhenomenonService;
import com.zmn.oms.services.interfaces.quotation3.OrderQuotationProcessService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 描述: 一口价订单报价表实现类
 *
 * @author chengguang
 * @since 2022/09/19 16:14
 */
@Service
@Slf4j
public class OrderFinalPriceQuotationBServiceImpl implements OrderFinalPriceQuotationBService {

    @Resource
    private OrderFinalPriceQuotationService orderFinalPriceQuotationService;

    @Resource
    private OrderQuotationProcessService orderQuotationProcessService;

    @Resource
    private OrderWorkService orderWorkService;

    @Resource
    private OrderFaultPhenomenonService orderFaultPhenomenonService;
    @Resource
    private PhenomenonListRemoteService phenomenonListRemoteService;

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private FixedFlowRemoteService fixedFlowRemoteService;

    @Override
    public OrderFinalPriceQuotationDRO getOrderFinalPriceQuotationByOrderIdAndWorkId(Long orderId, Long workId) {

        List<OrderFinalPriceQuotation> orderFinalPriceQuotations = orderFinalPriceQuotationService.
                listByQuery(OrderFinalPriceQuotationQuery.builder().orderId(orderId).workId(workId).build());
        if (CollectionUtil.isNotEmpty(orderFinalPriceQuotations)) {
            return BeanUtil.copyProperties(orderFinalPriceQuotations.get(0), OrderFinalPriceQuotationDRO.class);
        }
        return null;
    }

    @Override
    public void initOrderFinalPriceQuotationData(OrderFinalPriceQuotationDataDIO orderFinalPriceQuotationDataDIO) {

        Long orderId = orderFinalPriceQuotationDataDIO.getOrderId();
//        Long workId = orderFinalPriceQuotationDataDIO.getWorkId();
//        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (!Objects.equals(orderFinalPriceQuotationDataDIO.getFinalPrice(), GlobalConsts.YES)) {
            return;
        }
        if (Objects.isNull(orderFinalPriceQuotationDataDIO.getProductId())){
            return;
        }
        OrderQuotationProcess process = new OrderQuotationProcess();
        process.setOrderId(orderId);
        process.setCheckProductStatus(GlobalConsts.YES);
        process.setCreater(orderFinalPriceQuotationDataDIO.getOperator());
        process.setUpdater(orderFinalPriceQuotationDataDIO.getOperator());
        process.setCreateTime(DateUtil.getNow());
        process.setUpdateTime(DateUtil.getNow());
        List<OrderFaultPhenomenon> orderFaultPhenomena = orderFaultPhenomenonService.listByOrderId(orderId);
        if (CollectionUtil.isNotEmpty(orderFaultPhenomena)){
            process.setConfirmStatus(GlobalConsts.YES);
        }
        orderQuotationProcessService.updateByOrderIdSelectiveSrcMaster(process);
    }

    @Override
    public void saveOrderFinalPriceQuotation(OmsOperator operator, OrderFinalPriceQuotation quotation, OrderWork orderWork, OrderProduct orderProduct) {
        // 冗余处理故障现象
        if (NumberUtil.isNullOrZero(quotation.getPhenId())
                && NumberUtil.isNotNullOrZero(quotation.getServItemId())
                && Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)
                && Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)
        ) {
            // 通过服务项ID，完善故障现象信息
            FixedPhenoFilterItemQuery itemQuery = FixedPhenoFilterItemQuery.builder()
                    .bizType(orderWork.getBizType())
                    .servCategId(orderWork.getServCategId())
                    .ecProductId(orderProduct.getShowProductId())
                    .itemId(quotation.getServItemId())
                    .brandId(orderProduct.getBrandId())
                    .categId(orderProduct.getCategId())
                    .channelId(orderWork.getChannelId())
                    .cityId(orderWork.getCityId())
                    .build();

            log.info("通过服务项ID查询故障现象 入参：{}", JSON.toJSONString(itemQuery));
            com.zmn.common.dto2.ResponseDTO<List<PhenomenonDRO>> responseDTO = fixedFlowRemoteService.listPhenoFilterItemByQuery(itemQuery);
            log.info("通过服务项ID查询故障现象 出参：{}", JSON.toJSONString(responseDTO));
            if (responseDTO.isSuccess() && com.zmn.common.utils.collection.CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
                PhenomenonDRO phenomenonDRO = responseDTO.getData().get(0);
                quotation.setPhenId(phenomenonDRO.getPhenId());
                quotation.setPhenName(phenomenonDRO.getPhenName());
                quotation.setDeteTime(phenomenonDRO.getMaintainTime());
            }
        }

        // 提交了故障现象
        if (NumberUtil.isNotNullOrZero(quotation.getPhenId())) {
            OrderFaultPhenomenon orderFaultPhenomenon = new OrderFaultPhenomenon();
            orderFaultPhenomenon.setOrderId(quotation.getOrderId());
            if (NumberUtil.isNullOrZero(quotation.getDeteTime())) {
                com.zmn.common.dto2.ResponseDTO<PhenomenonDRO> phenResponseDTO = phenomenonListRemoteService.getById(quotation.getPhenId());
                if (Objects.nonNull(phenResponseDTO.getData())) {
                    PhenomenonDRO phenomenonDRO = phenResponseDTO.getData();
                    orderFaultPhenomenon.setPhenId(phenomenonDRO.getPhenId());
                    orderFaultPhenomenon.setPhenName(phenomenonDRO.getPhenName());
                    orderFaultPhenomenon.setDeteTime(phenomenonDRO.getMaintainTime());
                }
            } else {
                orderFaultPhenomenon.setPhenId(quotation.getPhenId());
                orderFaultPhenomenon.setPhenName(quotation.getPhenName());
                orderFaultPhenomenon.setDeteTime(quotation.getDeteTime());
            }

            orderFaultPhenomenon.setCreater(Optional.ofNullable(operator.getOperator()).orElse("系统"));
            orderFaultPhenomenon.setCreateTime(DateUtil.getNow());

            orderFaultPhenomenonService.insertList(Lists.newArrayList(orderFaultPhenomenon));

            if (StringUtil.isBlank(quotation.getPhenName())) {
                quotation.setPhenName(orderFaultPhenomenon.getPhenName());
            }
        }

        orderFinalPriceQuotationService.insert(quotation);

        OrderFinalPriceQuotationDataDIO dio = new OrderFinalPriceQuotationDataDIO();
        dio.setOrderId(quotation.getOrderId());
        dio.setWorkId(quotation.getWorkId());
        dio.setProductId(orderWork.getProductId());
        dio.setFinalPrice(orderWork.getFinalPrice());
        dio.setOperator(Optional.ofNullable(operator.getOperator()).orElse("系统"));
        this.initOrderFinalPriceQuotationData(dio);
    }

    @Override
    public void updateOrderFinalPriceQuotation(OmsOperator operator, OrderFinalPriceQuotation quotation, OrderWork orderWork, OrderProduct orderProduct) {

        // 提交了故障现象
        if (NumberUtil.isNotNullOrZero(quotation.getPhenId())) {
            OrderFaultPhenomenon orderFaultPhenomenon = new OrderFaultPhenomenon();
            orderFaultPhenomenon.setOrderId(quotation.getOrderId());
            if (NumberUtil.isNullOrZero(quotation.getDeteTime())) {
                com.zmn.common.dto2.ResponseDTO<PhenomenonDRO> phenResponseDTO = phenomenonListRemoteService.getById(quotation.getPhenId());
                if (Objects.nonNull(phenResponseDTO.getData())) {
                    PhenomenonDRO phenomenonDRO = phenResponseDTO.getData();
                    orderFaultPhenomenon.setPhenId(phenomenonDRO.getPhenId());
                    orderFaultPhenomenon.setPhenName(phenomenonDRO.getPhenName());
                    orderFaultPhenomenon.setDeteTime(phenomenonDRO.getMaintainTime());
                }
            } else {
                orderFaultPhenomenon.setPhenId(quotation.getPhenId());
                orderFaultPhenomenon.setPhenName(quotation.getPhenName());
                orderFaultPhenomenon.setDeteTime(quotation.getDeteTime());
            }

            orderFaultPhenomenon.setCreater(Optional.ofNullable(operator.getOperator()).orElse("系统"));
            orderFaultPhenomenon.setCreateTime(DateUtil.getNow());

            orderFaultPhenomenonService.deleteByOrderId(orderWork.getOrderId());
            orderFaultPhenomenonService.insertList(Lists.newArrayList(orderFaultPhenomenon));

            if (StringUtil.isBlank(quotation.getPhenName())) {
                quotation.setPhenName(orderFaultPhenomenon.getPhenName());
            }
        }

        orderFinalPriceQuotationService.updateByKey(quotation);

        OrderFinalPriceQuotationDataDIO dio = new OrderFinalPriceQuotationDataDIO();
        dio.setOrderId(quotation.getOrderId());
        dio.setWorkId(quotation.getWorkId());
        dio.setProductId(orderWork.getProductId());
        dio.setFinalPrice(orderWork.getFinalPrice());
        dio.setOperator(Optional.ofNullable(operator.getOperator()).orElse("系统"));
        this.initOrderFinalPriceQuotationData(dio);
    }
}


